package com.frankie.weibo.miweibo.api;

import com.frankie.weibo.miweibo.api.interf.IMiCallback;
import com.frankie.weibo.miweibo.bean.Error;

import org.json.JSONObject;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Frankie on 2016/8/29.
 */

public class NewCallback<T> {

    private IMiCallback<T> miCallback;
    private Decorator<T> decorator;
    private Subscription subscription;

    public NewCallback(IMiCallback<T> miCallback, Decorator<T> decorator){
        this.miCallback = miCallback;
        this.decorator = decorator;
    }

    public void onSuccess(JSONObject resultJson){
        subscription = Observable.just(resultJson).map(new Func1<JSONObject, T>() {
            @Override
            public T call(JSONObject resultJson) {
                return decorator.decorate(resultJson);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(successAction());
    }

    public void onError(Error error){
        subscription = Observable.just(error).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(errorAction());
    }

    private Action1 successAction(){
        return new Action1<T>(){
            @Override
            public void call(T t) {
                miCallback.onSuccess(t);
                subscription.unsubscribe();
            }
        };
    }

    private Action1 errorAction(){
        return new Action1<Error>(){
            @Override
            public void call(Error error) {
                miCallback.onError(error);
                subscription.unsubscribe();

                /**
                 * @TODO 这里可以做一些error的逻辑判断
                 */

            }
        };
    }

    public interface Decorator<T> {
        T decorate(JSONObject resultJson);
    }

}
